import React, { useState, useEffect } from 'react';
import { Tooltip, Icon, Button, Table, Empty, message, Popconfirm, Input } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import EmptyDataImg from '@images/empty-data-blue.png';
import { getDictsList, deleteDicts, downloadDict } from '@api/dict';
import DictConfigModel from './components/dict-config-model';
import './index.less';

const prefixCls = 'dict-config';
const Search = Input.Search;
const DICT_NAME_MAP = {
  username: '用户名字典',
  password: '密码字典'
};

function DictConfig() {
  const [count, setCount] = useState(0);
  const [filter, setFilter] = useState({ page: 1, pageSize: 10 });
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [dataSource, setDataSource] = useState([]);

  function getList() {
    setLoading(true);
    getDictsList(filter)
      .then(res => {
        const data = _.get(res, 'data.data.list', []);
        const count = _.get(res, 'data.data.count', 0);
        setDataSource(data);
        setCount(count);
      })
      .catch(() => {
        message.error('获取列表失败！');
      })
      .finally(() => {
        setLoading(false);
      });
  }

  useEffect(() => {
    getList();
  }, [filter]);

  const downloadFile = record => {
    downloadDict({ fileName: record.fileName, isBuiltIn: record.isBuiltIn })
      .then(() => {
        message.success('下载成功！');
      })
      .catch(() => {
        message.error('下载失败！');
      });
  };

  const handleDeleteDict = ids => {
    setLoading(true);
    deleteDicts(ids)
      .then(() => {
        message.success('删除成功！');
        getList();
        setSelectedRowKeys([]);
      })
      .catch(() => {
        message.error('删除失败');
        setLoading(false);
      });
  };

  const getSize = size => {
    const unitMap = {
      MB: 1024 * 1024,
      KB: 1024,
      B: 1
    };
    const unit = _.findKey(unitMap, u => size / u > 0.1);
    // 精确到小数后两位
    return `${Math.round((size / unitMap[unit]) * 100) / 100}${unit}`;
  };

  const onTableChange = (pagination, filters, sorter) => {
    setFilter({
      ...filter,
      page: pagination.current,
      pageSize: pagination.pageSize,
      type: filters.type || [],
      createdSort: sorter.order === 'ascend' ? 1 : -1
    });
  };

  const columns = [
    {
      title: '字典名称',
      dataIndex: 'name'
    },
    {
      title: '字典类型',
      dataIndex: 'type',
      render: type => DICT_NAME_MAP[type],
      filters: [
        {
          text: '用户名字典',
          value: 'username'
        },
        {
          text: '密码字典',
          value: 'password'
        }
      ],
      filteredValue: filter.type || []
    },
    {
      title: '大小',
      dataIndex: 'size',
      render: size => getSize(size)
    },
    {
      title: '上传时间',
      dataIndex: 'created',
      render: created => moment(created).format('YYYY-MM-DD HH:mm:ss'),
      sorter: (a, b) => a.created - b.created
    },
    {
      title: '字典分类',
      dataIndex: 'isBuiltIn',
      render: isBuiltIn => (isBuiltIn ? '系统默认' : '自定义')
    },
    {
      title: '操作',
      render: record => (
        <div>
          <Button type="link">
            <a onClick={() => downloadFile(record)}>下载</a>
          </Button>
          <Popconfirm
            placement="bottomRight"
            title={'确定删除选择的字典吗？'}
            onConfirm={() => handleDeleteDict({ ids: [record._id] })}
            okText="确定"
            cancelText="取消"
            disabled={record.isBuiltIn}
          >
            <Button
              type="link"
              style={{ color: record.isBuiltIn ? 'rgba(0, 0, 0, 0.25)' : 'red' }}
              disabled={record.isBuiltIn}
            >
              删除
            </Button>
          </Popconfirm>
        </div>
      )
    }
  ];

  const rowSelection = {
    onChange: selectedRowKeys => {
      setSelectedRowKeys(selectedRowKeys);
    },
    getCheckboxProps: record => ({
      disabled: record.isBuiltIn
    })
  };

  return (
    <div className={prefixCls}>
      <div className={`${prefixCls}-page-title`}>
        字典配置
        <Tooltip
          className="info"
          placement="right"
          overlayClassName={`${prefixCls}-page-title-desc`}
          title="添加字典后，可在弱口令下发检测时选择对应的字典"
        >
          <Icon type="exclamation-circle" />
        </Tooltip>
      </div>
      <div className={`${prefixCls}-operate`}>
        <div>
          <Button type="primary" onClick={() => setVisible(true)}>
            添加字典
          </Button>
          <Popconfirm
            placement="bottomRight"
            disabled={selectedRowKeys.length === 0}
            title={'确定删除选择的字典吗？'}
            onConfirm={() => handleDeleteDict({ ids: selectedRowKeys })}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="danger"
              className={`${prefixCls}-operate-btn`}
              disabled={selectedRowKeys.length === 0}
              loading={loading}
            >
              批量删除
            </Button>
          </Popconfirm>
        </div>
        <div>
          <Search
            enterButton
            placeholder="请输入字典名称搜索"
            allowClear
            onSearch={value => {
              setFilter({ ...filter, page: 1, search: value.trim() });
            }}
          />
        </div>
      </div>

      {filter.search || count ? (
        <div>
          <div className={`${prefixCls}-header-count`}>共有 “{count} “个字典</div>
          <Table
            rowKey={'_id'}
            rowSelection={rowSelection}
            loading={loading}
            columns={columns}
            pagination={{
              total: count,
              current: filter.page,
              pageSize: filter.pageSize,
              showQuickJumper: true,
              pageSizeOptions: ['10', '20', '50', '100'],
              showSizeChanger: true,
              showTotal: num => `共 ${num} 条`,
              size: 'small'
            }}
            dataSource={dataSource}
            getPopupContainer={triggerNode => triggerNode.parentNode}
            onChange={onTableChange}
          />
        </div>
      ) : (
        <Empty
          image={EmptyDataImg}
          imageStyle={{
            margin: '120px 0 24px',
            height: 296
          }}
          description={
            <div>
              <span style={{ color: '#2A2B30' }}>您还未创建过字典</span>
              <p style={{ marginTop: 8, color: '#999EA8' }}>
                添加字典后，可在弱口令下发检测时选择对应的字典，
                <br />
                您可以通过左上角按钮添加
              </p>
            </div>
          }
        />
      )}
      <DictConfigModel modalVisible={visible} changeModalVisible={setVisible} getList={getList} />
    </div>
  );
}

export default DictConfig;
